﻿////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// <copyright>Copyright 2008-2011 Andreas Huber Doenni</copyright>
// Distributed under the Microsoft Public License (Ms-PL).
// See accompanying file License.txt or copy at http://mews.codeplex.com/license.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Mews.Mime
{
    using System;
    using System.IO;

    /// <summary>Represents a message (see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a> 2.3.).</summary>
    /// <threadsafety static="true" instance="false"/>
    public sealed class Message : Entity<Message>
    {
        /// <summary>Initializes a new instance of the <see cref="Message"/> class.</summary>
        public Message()
        {
            var mimeVersionField = new UnstructuredHeaderField("MIME-Version") { Body = "1.0" };
            this.Fields.Add(mimeVersionField);
        }

        /// <summary>Writes the message into <paramref name="stream"/>.</summary>
        /// <exception cref="ArgumentNullException"><paramref name="stream"/> equals <c>null</c>.</exception>
        public void WriteTo(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            this.WriteToImpl(stream);
        }

        /// <summary>Returns the return value of <see cref="Parse(Stream, int)"/>(<paramref name="stream"/>, 8192).
        /// </summary>
        public static Message Parse(Stream stream)
        {
            return Parse(stream, Settings.DefaultPhysicalStreamBufferSize);
        }

        /// <summary>Converts the message in <paramref name="stream"/> into its in-memory equivalent.</summary>
        /// <param name="stream">The stream to read from.</param>
        /// <param name="bufferSize">The size of the temporary in-memory buffer that is allocated to read from
        /// <paramref name="stream"/>.</param>
        /// <exception cref="ArgumentException"><paramref name="stream"/> contains at least one line that is longer than
        /// <paramref name="bufferSize"/>.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="stream"/> equals <c>null</c>.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="bufferSize"/> is zero or negative.</exception>
        public static Message Parse(Stream stream, int bufferSize)
        {
            return ParseHelper.Parse<MessageProcessor, Message>(stream, bufferSize);
        }
    }
}
